from odoo import fields, models, api
from ast import literal_eval
from odoo.osv.expression import AND

class OrderMeterialLine(models.Model):
    _name = 'order.meterial.line'
    _description = '物料汇总明细'

    meterial_id = fields.Many2one('order.meterial', string='物料汇总')
    product_id = fields.Many2one('product.product', string='BOM物料')
    product_uom = fields.Many2one('uom.uom', related='product_id.uom_id', string='BOM物料单位', store=True)
    product_qty = fields.Float(string='BOM物料数量')
    real_product = fields.Many2one('product.product', string='实用物料')
    real_product_uom = fields.Many2one('uom.uom', related='real_product.uom_id', string='实用物料单位', store=True)
    real_product_qty = fields.Float(string='实用物料数量')
    optional_materials = fields.Many2many('product.product', 'sale_order_optional_meterials', string='可选物料')
    rule_domain = fields.Char(string='产成品预筛选条件')
    product_domain = fields.Char(string='替代物料预筛选条件')
    convertible_ratio = fields.Float(string='转换比例', compute='_compute_convertible_ratio', inverse="_inverse_convertible_ratio")

    @api.depends('real_product_qty')
    def _compute_convertible_ratio(self):
        for rec in self:
            rec.convertible_ratio = rec.real_product_qty / rec.product_qty

    @api.onchange('convertible_ratio')
    def _inverse_convertible_ratio(self):
        self.real_product_qty = self.product_qty * self.convertible_ratio

